﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Carmall.Web.Models;

using Carmall.Entity;
using Carmall.BLL;

namespace Carmall.Web.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public IFormsAuthenticationService FormsService { get; set; }
        public IAccountUserService UserService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (UserService == null) { UserService = new AccountUserServices(); }

            base.Initialize(requestContext);
        }

        public ActionResult Index()
        {

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult Success()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string ReturnUrl,LogOnModel model)
        {
            if (ModelState.IsValid)
            {
                UsersInfo user = UserService.ValidateUser(model.UserName, model.Password);
                if (user != null)
                {
                    FormsService.SignIn(model.UserName, true);
                    Session["CurrentUser"] = user;
                    Session["UserID"] = user.UserID;
                    if (!String.IsNullOrEmpty(ReturnUrl))
                    {
                        return Redirect(ReturnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Users");
                    }
                }
                else
                {
                    ModelState.AddModelError("Error", "提供的用户名或密码不正确。");
                }
            }

            ModelState.AddModelError("Error", "请输入用户名和密码。");
            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View("Index", model);
        }

        public ActionResult LogOff()
        {
            FormsService.SignOut();
            Session.Abandon();
            return RedirectToAction("Index", "Home");
        }
    }
}
